//wiadomosci wstawia do kolejki i wysyla w watku

import java.net.Socket;
import java.io.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ConnectionWriter extends Thread {
	private Connection connection;
	private BlockingQueue<Message> messages; //kolejka wiadomosci
	private Socket socket;
	private int size = 20; //rozm kolejki
	private ObjectOutputStream outStream; 
	
	public ConnectionWriter(Connection c) {
		connection = c;
		socket = c.socket;
		messages = new ArrayBlockingQueue<Message>(20);
		try {
		outStream = new ObjectOutputStream(socket.getOutputStream()); 
		} catch(Exception e) { System.out.println(e.getMessage()); }
	}
	
	public void addToQueue(Message m) {
		messages.add(m);
	}
	
	private void sendMessage(Message m) { //wysylanie z serializacja	
		try {
			//outStream.reset();
			outStream.writeObject(m);
			//outStream.flush();
		} catch (IOException e2) { //awaria
				System.out.println(e2.getMessage());
				connection.invokeLater(new Runnable() {
					public void run() {
						connection.connectionClosed();
					}
				});
				return;
		}
	}
	
	public void run() {
		while(true) {
			try {
			Message m = messages.take();
			if(m.getCommand().equals("WRITER_END"))
			{
				System.out.println("Zamykam pisarza") ;
				break ;
			}
				
			sendMessage(m);
			System.out.println("wysylam wiadomosc o typie " + m.getType()) ;
			} catch (InterruptedException e1)  { 
				return;
			}
		}
	}

}